//
//  HZRefreshControl.swift
//  weibo
//
//  Created by 张宏芝 on 15/9/8.
//  Copyright © 2015年 kama. All rights reserved.
//

import UIKit

// 系统高度默认是60
private let HZRefreshControlMaxOffSet:CGFloat = -60

class HZRefreshControl: UIRefreshControl {
    
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.stopAnimation()
    }
    
    override init() {
        super.init()
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init()
        setupUI()
    }
    
//    监听frame的主要方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if frame.origin.y > 0{
            return
        }
//        如果正在刷新
        if refreshing{
            refreshView.loadingAnimation()
            return
        }
        
        if frame.origin.y < HZRefreshControlMaxOffSet && !refreshView.rotateFlag {
            print("反过来")
            refreshView.rotateFlag = true
        } else if frame.origin.y >= HZRefreshControlMaxOffSet && refreshView.rotateFlag {
            print("转过去")
            refreshView.rotateFlag = false
        }
    }
    
//    销毁监听方法
    deinit{
        self.removeObserver(self, forKeyPath: "frame")
    }
//    自动布局
    private func setupUI(){
        
//        KVO :监听frame的改变
        self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
        tintColor = UIColor.clearColor()
        addSubview(refreshView)
        refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size)
        
//        refreshView.translatesAutoresizingMaskIntoConstraints = false
//        self.addConstraint(NSLayoutConstraint(item: refreshView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem:self, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: -40))
//        self.addConstraint(NSLayoutConstraint(item: refreshView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant:0))
    }
//    懒加载控件
    private lazy var refreshView = HZRefreshView.refreshView()
}

/// 新创建一个UIView类,只是负责界面的现实
class HZRefreshView: UIView {
    
//    动画的标记
    private var rotateFlag = false{
        didSet{
            rotateTipAnimation()
        }
    }
//    加载图标
    @IBOutlet weak var loadingView: UIImageView!
//    下拉刷新
    @IBOutlet weak var TipView: UIView!
//    下拉刷新图标
    @IBOutlet weak var TipImage: UIImageView!
    
//    加载XIB,将XIB与HMRefreshView建立联系
    class func refreshView() ->HZRefreshView {
        return NSBundle.mainBundle().loadNibNamed("HZRefreshView", owner: nil, options:nil).last as! HZRefreshView
    }
//    下拉刷新的旋转图标动画
    private func rotateTipAnimation(){
        var angle = CGFloat(M_PI)
        angle += rotateFlag ? -0.01 : +0.01
        UIView.animateWithDuration(0.5) { // 没有参数没有返回值的时候,后边的代码可以省略() -> Void in
//            闭包中加上self(切记)
            self.TipImage.transform = CGAffineTransformRotate(self.TipImage.transform, angle)
        }
    }
    
//    加载动画
    private func loadingAnimation(){
        let loadingKey = "loadingKey"
        if loadingView.layer.animationForKey(loadingKey) != nil{
            return
        }
        TipView.hidden = true
        let animation = CABasicAnimation(keyPath:"transform.rotation")
        animation.duration = 2
        animation.toValue = 2 * M_PI
        animation.repeatCount = MAXFLOAT
        loadingView.layer.addAnimation(animation, forKey: loadingKey)
    }
//    停止动画
    private func stopAnimation(){
        TipView.hidden = false
        loadingView.layer.removeAllAnimations()
    }
    
}